﻿var dataList = []; //图片查看器-图片数组
//设置图片查看器 //setImgView(null, item.Img1, "1_" + de + "_" + i);
function setImgView(obj, i) {
    dataList = [];
    var imgItem = $(obj).parent().parent().find("img");
    for (var i = 0; i < imgItem.length; i++) {
        dataList.push(imgItem[i].src);
    }
    var options = {
        dataList: dataList,
        currentSrc: $(obj).attr("src")
    };
    ImgView("imgView", options);
}
var tifid = "";
var shopName = "";//店铺名称
var checkDate = "";//时间

var GetRequest = function () {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
//页面第一次加载的时候数据
var LoadData = function () {
    var Request = new Object();
    Request = GetRequest();
    tifid = Request['tifid'];
    shopName = Request['shopName'];
    checkDate = Request['checkDate'];
    $("#search-Time").append('<option value=' + checkDate + '>' + checkDate + '</option>');

    loadTopTab();
    ShopList("");
    if (shopName != "" && shopName != undefined)
        getDateTime(shopName);//进来时获取时间
    loadStatusAllList();
    if (checkDate == undefined)
        $("#search-Time").find("option").remove();//移除原来的数据
}

var imgIdlist = "";
var parentCode = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
//创建项目巡检总结
var createSummaryList = function (list) {
    var table = $('#tif_SummaryList');
    if (list != null && list.length > 0) {
        //清空
        table.empty();
        var tableHtml = '<tbody><tr><td style="width: 26px; text-align:center;vertical-align: middle;" rowspan="' + list.length + 1 + '">巡店总结</td><td style="width: 150px;">项目问题</td><td style="min-width: 280px; width: auto;">问题汇总描述</td><td style="min-width: 280px; width: auto;">建议改善方法</td></tr>';
        $.map(list, function (item) {
            tableHtml += '<tr><td style= "width: 150px;"><span class="tis_projectProblem">' + item.tis_projectProblem + '</span></td><td style="min-width: 280px; width: auto;"><span class="tis_problemDescription">' + item.tis_problemDescription + '</span></td><td style="min-width: 280px; width: auto;"><span class="tis_advice">' + item.tis_advice + '</span></td></tr>';
        });
        tableHtml += '</tbody>';
        table.append(tableHtml);
    }
}
//加载头部数据
var loadTopTab = function () {
    $.post("/ShopTask/TaskHandler.ashx", {
        "action": "GetBaseModelTab",
        "tifid": tifid,
        "shopName": shopName,
        "checkDate": checkDate
    }, function (data) {
        if (data.Success == true) {
            var temp_item = data.Data[0];
            $(".tif_checkCount").html(temp_item.tif_checkCount);
            $(".tif_id").html(temp_item.tif_id);
            $(".tif_shopName").html(temp_item.tif_shopName);
            $(".tif_shopCode").html(temp_item.tif_shopCode);
            $(".kddate").html(temp_item.kddate.substring(0, 10));
            $(".tif_questionCount").html(temp_item.tif_questionCount);
            $(".tif_score").html(temp_item.tif_score);
            $(".tif_checkDate").html(temp_item.tif_checkDate.substring(0, 10));
            $(".weekWeather").html(temp_item.weekWeather);
            var lastCheckDate = temp_item.lastCheckDate;
            if (lastCheckDate == "0001-01-01T00:00:00") {
                $(".lastCheckDate").html("——");
                $(".lastscore").html("——");
                $(".lasquestionCount").html("——");
            }
            else {
                $(".lastCheckDate").html(lastCheckDate.substring(0, 10));
                $(".lastscore").html(temp_item.lastscore);
                $(".lasquestionCount").html(temp_item.lasquestionCount);
            }
            $(".tif_storeManager").html(temp_item.tif_storeManager);
            $(".tif_shopManager").html(temp_item.tif_shopManager);
            $(".tif_shopLevel").html(temp_item.tif_shopLevel);
            $(".tif_supervisor").html(temp_item.tif_supervisor);
            $(".tif_captain").html(temp_item.tif_captain);
            createSummaryList(temp_item.tif_SummaryList);
            $("#search-shop").val(temp_item.shopName);
        }
    });
}
//检查数据加载
function loadStatusAllList() {
    var httml = "";
    var obj = [];
    $.post("/ShopTask/TaskHandler.ashx", {
        "action": "GetStatusCheck",
        "tifid": tifid,
        "shopName": shopName,
        "checkDate": checkDate,
        "ins_parentName": ""
    }, function (data) {
        $("#StatusList").html("");
        if (data.Success == false) {
            var html = "<div class='tabconten'><h2 style='text-align: center;'> 暂无检查数据</h2></div>'";
            $("#StatusList").append(html);
            return;
        }
        var map = {}, dest = [];
        for (var i = 0; i < data.Data.length; i++) {
            var ai = data.Data[i];
            if (!map[ai.ins_parentCode]) {
                dest.push({
                    Group: ai.ins_parentCode,
                    data: [ai]
                });
                map[ai.ins_parentCode] = ai;
            } else {
                for (var j = 0; j < dest.length; j++) {
                    var dj = dest[j];
                    if (dj.Group == ai.ins_parentCode) {
                        dj.data.push(ai);
                        break;
                    }
                }
            }
        }
        for (var de = 0; de < dest.length; de++) {
            var count = 0;
            var points = 0;
            var CheckScore = 0;
            var tidpoints = "";
            var html = '<div class="tabconten"> ';
            html += '<ul class="detail">';
            html += '<li class="FontStong"> parentName（<span class=""> CheckScore </span>分）</li>';
            html += '<li><span style="margin-left: 100px;"></span></li>';
            html += '    <li>查出问题数：<span class="FontRed "> checkErrorCount </span></li>';
            html += '    <li>扣分：<span class="FontRed"> checkPoints </span></li>';
            html += '</ul >';
            html += '</div>';
            html += '    <div class="clearfix smallsize-font small-font">';
            html += '        <table id="statusCheckTable" class="TableStyle" style="width: 100%;" border="1" cellspacing="0" cellpadding="0">';
            html += '            <tr>';
            html += '              <th class="Textcenter">序号</th>';
            html += '              <th style="width: 40%">检查项目</th>';
            html += '              <th class="Textcenter">分值</th>';
            html += '              <th class="Textcenter">扣分</th>';
            html += '              <th style="width: 30%">备注</th>';
            html += '              <th>图片</th>';
            html += '           </tr>';
            dest[de].data.map(function (item, i) {
                if (parseInt(item.tid_points) == 0) tidpoints = ""; else tidpoints = item.tid_points;

                html += "<tr> ";
                html += "<td class='Textcenter'>" + parseInt(i + 1) + "</td>";
                html += "<td>" + item.ins_checkContext + "</td>";
                html += "<td class='Textcenter'>" + item.ins_score + "</td>";
                html += "<td class='Textcenter'>" + tidpoints + "</td>";

                if (item.w_id > 0) {
                    //var url = '/PatrolShop/WorkOrder/OderMaster.aspx?mid=3232&tidId=' + item.tid_id;
                    //html += "<td>" + item.tid_remarks + "</br> <a href='#' class='OderMaster' onclick='OpenOderMaster(3232,\"" + url + "\")' >关联工单</a> " + "</td>";
                    html += "<td>" + item.tid_remarks + "</br> <a href='#' class='OderMaster' onclick='viewDetal(" + item.w_id + ")' >关联工单</a> " + "</td>";
                } else
                    html += "<td>" + item.tid_remarks + "</td>";

                html += "<td><div class='imgDiv'>";
                if (item.Img1 != null && item.Img1 != "" && item.Img1 != undefined) {
                    html += "<div><img src='" + item.Img1 + "' onClick='setImgView(this,0)'  class='img'></div>";//'  title='" + item.title1 + "'
                }
                if (item.Img2 != null && item.Img2 != "" && item.Img2 != undefined) {
                    html += "<div><img src='" + item.Img2 + "' onClick='setImgView(this,0)'  class='img' ></div>";//'  title='" + item.title2 + "'
                }
                if (item.Img3 != null && item.Img3 != "" && item.Img3 != undefined) {
                    html += "<div><img src='" + item.Img3 + "' onClick='setImgView(this,0)'  class='img' ></div>";//'  title='" + item.title3 + "'
                }
                html += "</div ></td > ";
                html += "</tr> ";
                points += item.tid_points;
                parentName = item.ins_parentName;
                CheckScore += item.ins_score;
                if (item.tid_points > 0) {
                    count++;
                }
            });
            html = html.replace("checkErrorCount", count);
            html = html.replace("checkPoints", points);
            html = html.replace("CheckScore", CheckScore);
            html = html.replace("parentName", parentName);
            html += "</div>";

            $("#StatusList").append(html);//处理完成后添加到页面
        }
    });

}
//获取店铺名称
function ShopList(shopName) {
    $.post("/ShopTask/TaskHandler.ashx", { "action": "GetShopNameList", "shopName": shopName }, function (data) {
        var ArrList = [];
        if (data.Success == true) {
            if (data.Data.length > 0) {
                data.Data.map(function (item, i) {
                    ArrList.push(item.tif_shopName);
                });
                $('#search-shop').typeahead({
                    source: ArrList,
                    items: 100
                });
            }
        }
    });
}
//查询巡检时间
function getDateTime(shopName) {
    if (shopName == undefined) return;
    $.post("/ShopTask/TaskHandler.ashx", { "action": "GetTimeList", "shopName": shopName }, function (data) {
        if (data.Success == true) {
            var OldTime = $("#search-Time").val();//保留旧值
            $("#search-Time").find("option").remove();//移除原来的数据

            if (data.Data.length > 0) {
                var sHtml = "";
                data.Data.map(function (item, i) {
                    if (OldTime != undefined && item.tif_checkDate == OldTime) {
                        // console.log(item.tif_checkDate.length);
                        sHtml += '<option value=' + item.tif_checkDate + ' selected="selected">' + item.tif_checkDate + '</option>';
                    }
                    else {
                        // console.log(item.tif_checkDate.length);
                        sHtml += '<option value=' + item.tif_checkDate + '>' + item.tif_checkDate + '</option>';
                    }
                });
                // console.log(data.Data.length);
                $("#search-Time").append(sHtml);

            }
        }
    });
}
//查看工单详情
function viewDetal(w_id) {
    var index = layer.open({
        type: 2,
        anim: 2,
        isOutAnim: true,
        title: '查看工单',
        content: 'WorkOrder/OrderInfo.aspx?viewState=Query&IsEdit=1&wId=' + w_id,
        area: ['800px', '600px'],
        maxmin: true,
        cancel: function (index, layero) {
            layer.close(index);
        }
    });
    layer.full(index);
}
//页面加载后执行
$(function () {
    //查询按钮
    $("#search-Btn").click(function () {
        tifid = "";
        shopName = $("#search-shop").val();
        checkDate = $("#search-Time").val();
        loadTopTab();
        loadStatusAllList();
    });
    //页面加载时，加载所有数据
    LoadData();
    //打印
    $("#BtnPrint").click(function () {
        shopName = $("#search-shop").val();
        $(".imgDiv").hide();//图片隐藏后再打印
        $("#RemovePrint").hide();  //按钮隐藏
        $(".OderMaster").hide();//关联工单隐藏
        //$("body").height() = $(".borderGray").height() + 10;
        bdhtml = window.document.body.innerHTML;
        sprnstr = "<!--startprint-->"; //开始打印标识字符串有17个字符
        eprnstr = "<!--endprint-->"; //结束打印标识字符串
        prnhtml = bdhtml.substring(0, bdhtml.indexOf(sprnstr));//从头开始到需要移除的标识符数据
        prnhtml += bdhtml.substring(bdhtml.indexOf(eprnstr) + 15);//从被移除后的数据开始到结尾
        window.document.body.innerHTML = prnhtml; //把需要打印的指定内容赋给body.innerHTML
        window.print(); //调用浏览器的打印功能打印指定区域
        //window.document.body.innerHTML = bdhtml;//重新给页面内容赋值；
        // window.location.reload();
        var Request = new Object();
        Request = GetRequest();
        mid = Request['mid'];

        // checkDate = $("#search-Time").val();
        var url = '/PatrolShop/ShopInspectionResults.aspx?mid=' + mid + '&shopName=' + encodeURI(encodeURI(shopName)) + '&checkDate=' + checkDate;
        window.parent.CloseThis(mid);
        window.parent.ChildOpenNowWin(mid, "巡检结果表", url);
    });

    //隐藏图片
    var hideImg = function () {
        $(".imgPreview").hide();
    }

    $(document).keyup(function (event) {
        switch (event.keyCode) {
            case 27:
                hideImg();
            case 96:
                hideImg();
        }
    });

    $(".imgPreview").mouseleave(function () {
        hideImg();
    });

    //离开店铺输入的时候触发，查询时间
    $("#search-shop").blur(function () {
        var shopName = $(".active").attr("data-value");
        if (shopName != "" && shopName != undefined)
            getDateTime(shopName);
        else {
            $("#search-Time").find("option").remove();//移除原来的数据
        }
    });

    $("#search-Time").click(function () {
        return;
    });

    $("#BtnExport").click(function () {
        shopName = $("#search-shop").val();
        checkDate = $("#search-Time").val();
        if (Y.checkNull(shopName) || Y.checkNull(checkDate)) {
            return false;
        } else {
            $.post("/ShopTask/TaskHandler.ashx",
                {
                    "action": "ExportShopInspectionResults",
                    "tifid": tifid,
                    "shopName": shopName,
                    "checkDate": checkDate
                },
                function (data) {
                    if (data.Data != null) {
                        console.log(data);
                        outExcle(data.Data);
                    }
                });
        }
    });
});


